package ro.isdc.training.ejb3.misc.domain;

import java.sql.Timestamp;
import java.util.Date;

import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Listener used for auditing Business Entities
 * 
 * @author Andrei Chirila
 */
public class BusinessEntityAuditListener {

  private static final Log LOGGER = LogFactory
    .getLog(BusinessEntityAuditListener.class);

	/**
	 * Sets the creation and last update timestamp when saving an entity.
	 * 
	 * @param entity the entity to save.
	 */
	@PrePersist
	public void auditSave(final BusinessEntity entity) {
	  LOGGER.info("Save auditing: ");
		Timestamp currentTimestamp = new Timestamp(new Date().getTime());
		entity.setCreationTimestamp(currentTimestamp);
		entity.setLastUpdateTimestamp(currentTimestamp);
	}
	
	/**
	 * Sets the last update timestamp when updating an entity.
	 * 
	 * @param entity the entity to update
	 */
	@PreUpdate
	public void auditUpdate(final BusinessEntity entity) {
	  LOGGER.info("Update auditing: ");
		entity.setLastUpdateTimestamp(new Timestamp(new Date().getTime()));
	}

}
